import { defineStore } from 'pinia';
import router from '@/router';
import { ref, computed } from 'vue';

export default defineStore(
  'tabs',
  () => {
    const tabs = ref([
      {
        title: '工作台',
        name: 'workBench',
        url: '/',
        closable: false
      }
    ]);
    const current = ref();
    const openedView = computed(() => tabs.value.map((item) => item.name));

    const getTabIndex = (url) => {
      return tabs.value.findIndex((item) => item.url === url);
    };

    const openTab = ({ url, title, query, name, isJump = true }) => {
      const idx = getTabIndex(url);
      if (idx === -1) {
        tabs.value.push({ url, title, name });
      }
      current.value = url;
      isJump && router.push({ path: url, query });
    };

    const closeTab = ({ url }) => {
      const idx = getTabIndex(url);
      tabs.value.splice(idx, 1);
      if (current.value === url) {
        let tab = tabs.value[idx] || tabs.value[idx - 1];
        current.value = tab?.url;
      }
      router.push(current.value || '/');
    };

    const closeAllTab = () => {
      tabs.value = tabs.value.filter((t) => t.closable === false);
      if (tabs.value.length) {
        if (-1 === getTabIndex(current.value)) {
          openTab(tabs.value[0]);
        }
      } else {
        router.push('/');
      }
    };

    const reset = () => {
      tabs.value = tabs.value.filter((t) => t.closable === false);
      current.value = null;
    };

    return {
      tabs,
      current,
      closeTab,
      openedView,
      openTab,
      closeAllTab,
      getTabIndex,
      reset
    };
  },
  {
    persist: {
      enabled: true,
      strategies: [{ storage: sessionStorage, paths: ['tabs', 'current'] }]
    }
  }
);
